
<style lang="scss" scoped>
.container {
  padding: 0 16px;
  // .upload-demo{
  // 	width: 150px;
  // 	.el-upload {
  // 		display: inline-block;
  // 		text-align: center;
  // 		cursor: pointer;
  // 		outline: none;
  // 	}
  // }
}

.el-select .el-select--small {
  display: block !important;
}
</style>

<!-- 页面布局-->
<template>
  <div class="table">
    <!-- 主体区 -->
    <div class="container">
      <!-- 表单区 -->
      <div class="form-data-box">
        <el-form
          :model="formBean"
          :rules="validateRules"
          ref="form1"
          label-width="120px"
          class="ruleForm"
          style="width: 80%;"
        >
          <el-row style="margin-top: 18px;">
            <el-col :span="24">
              <el-form-item label="文件导入" prop="operateFileName">
                <div class="fxrow">
                  <el-input :readonly="readOnly" v-model="formBean.operateFileName"></el-input>
                  <el-upload
                    class="upload-demo"
                    action
                    multiple
                    :show-file-list="false"
                    accept=".zip"
                    :http-request="uploadFile"
                    :file-list="fileList"
                    :on-change="handleFileChange"
                  >
                    <el-button size="small" type="primary" style="vertical-align: top;">选择文件</el-button>
                  </el-upload>
                  <!-- <el-button size="small" type="primary" style="vertical-align: top;margin-left: 10px;min-width: 104px;" @click="downloadFile()">文件模板下载</el-button> -->
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div v-if="showTable">
        <div
          class="detailTitle fxrow"
          style="overflow: hidden;justify-content: space-between;margin-bottom: 5px;"
        >
          <div class="fxrow fxsc" style="flex: 1;">
            <table>
              <tr>
                <td>
                  <i class="el-icon-search"></i>
                </td>
                <td class="search_td">
                  <el-input
                    v-model="parampters.provinceName"
                    clearable
                    placeholder="省份"
                    class="handle-input mr10"
                  ></el-input>
                </td>
                <td class="search_td">
                  <el-input
                    v-model="parampters.cityName"
                    clearable
                    placeholder="地市"
                    class="handle-input mr10"
                  ></el-input>
                </td>
                <td class="search_td">
                  <el-input
                    v-model="parampters.dnsegNum"
                    clearable
                    placeholder="号段"
                    class="handle-input mr10"
                  ></el-input>
                </td>
                <td class="search_td">
                  <el-input
                    v-model="parampters.productName"
                    clearable
                    placeholder="产品名称"
                    class="handle-input mr10"
                  ></el-input>
                </td>
                <td class="search_td">
                  <el-input
                    v-model="parampters.cardFaceName"
                    clearable
                    placeholder="版面描述"
                    class="handle-input mr10"
                  ></el-input>
                </td>
                <!-- <td class="search_td">
                  <el-date-picker v-model="parampters.starttime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="开始时间" class="handle-input mr10" style="width:200px;">
                  </el-date-picker>
                </td>
                <td class="search_td">
                  <el-date-picker v-model="parampters.endtime"   type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="结束时间" class="handle-input mr10" style="width:200px;">
                  </el-date-picker>
                </td>-->
              </tr>
            </table>
          </div>
          <div>
            <el-button size="small" type="primary" @click="getTableData()">查询</el-button>
          </div>
        </div>
        <el-table
          :data="tableData"
          max-height="275"
          border
          :cell-class-name="changeColumnClass"
          :header-cell-style="{background:'#F3F3F3',color:'#606266'}"
          show-overflow-tooltip
          style="width: 100%"
          ref="multipleTable"
          :cell-style="{padding:'3px 0 !important'}"
        >
          <el-table-column type="index" label="序号" width="50" show-overflow-tooltip></el-table-column>
          <el-table-column
            prop="cardNum"
            label="申请数量"
            width="70"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="provinceName"
            label="省份"
            width="60"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="cityName"
            label="地市"
            width="60"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column prop="productName" label="产品名称" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column
            prop="dnsegNum"
            label="号段"
            width="80"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="spName"
            label="卡商"
            width="100"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column prop="cardFaceName" label="卡片图案" align="center" show-overflow-tooltip></el-table-column>
        </el-table>
        <div class="navigate-box">
          <div class="pagination">
            <el-pagination
              background
              @current-change="handleCurrentChange"
              :total="parampters.totalCount"
              @size-change="handleSizeChange"
              :current-page.sync="parampters.pageIndex"
              :page-sizes="[8, 20, 50, 100, 200]"
              :page-size="parampters.pageRows"
              layout="total, sizes, prev, pager, next"
            ></el-pagination>
          </div>
        </div>
      </div>
      <!-- 表单区END -->
      <!-- 按钮操作区 -->
      <span slot="footer" class="form-btn-box">
        <!-- <el-button v-if="!readOnly" @click="resetForm('form1')">重 置</el-button> -->
        <el-button
          v-if="!readOnly"
          type="primary"
          @click="submitForm()"
          v-loading.fullscreen.lock="fullscreenLoading"
        >提 交</el-button>
        <el-button @click="cnacelForm('form1')">取 消</el-button>
      </span>
      <!-- 按钮操作区END -->
    </div>
    <!-- 主体区END -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 提交表单的loading设置标识
      fullscreenLoading: false,
      firstLoadedData: "{}",
      // 新增用户表单信息
      formBean: {
        operateFileName: "" //上传图片
      },
      orgNotsele: true,
      // 表单校验规则
      validateRules: {
        operateFileName: [
          { required: true, message: "请上传文件", trigger: "blur" }
        ]
      },
      //所选记录id
      selectedId: "",
      //事物类型
      actType: "",
      // 表单只读状态
      readOnly: false,
      readOnlyEdt: false,
      //字典集
      dicts: {},
      cascaders: {},
      cascaderSelected: {},
      updimgurl: "",
      showTable: false,
      // 查询出的表格数据
      tableData: [],
      fileList: [],
      downloadFileUrl: "",
      // 筛选条件
      parampters: {
        //查询参数
        pageRows: 8, //每页行数
        pageIndex: 1, //当前页
        pageCount: 0, //总页数
        totalCount: 0, //总记录数
        province: null,
        city: null,
        provinceCode: "",
        provinceName: "",
        cityCode: "",
        cityName: "",
        productName: "",
        dnsegNum: "",
        cardFaceName: "",
        starttime: "",
        endtime: ""
      },
      previewId: ""
    };
  },
  props: {
    sourceData: {
      required: true
    }
  },
  // 进入页面加载数据
  mounted() {
    this.handleInitLoad();
  },
  methods: {
    /**
     * 组件初始化加载
     */
    handleInitLoad() {
      // this.initFormData();
      // this.getDownloadSampleUrl();
    },

    /**
     * 取消返回
     * @augments formName 表单名称
     */
    cnacelForm(formName) {
      this.$refs[formName].resetFields();
      this.$emit("cancel", this.cancelData);
    },
    /**
     * 重置表单
     * @augments formName 表单名称
     */
    resetForm(formName) {
      this.formBean = JSON.parse(this.firstLoadedData);
    },
    /**
     *初始化加载表单数据
     */
    initFormData() {
      this.selectedId = this.sourceData.seleid;
      this.actType = this.sourceData.actType;
      this.readOnlyEdt = true;
      if (this.actType == "view") {
        // 查看状态 标识表单只读
        this.readOnly = true;
      } else if (this.actType == "add") {
        this.readOnly = false;
        this.readOnlyEdt = false;
        //清空修改保存之后数据还存在的情况
        for (var key in this.formBean) {
          this.formBean[key] = "";
        }
      } else {
        this.readOnly = false;
      }
      if (this.$util.getLoginer().administrator == true) {
        this.orgNotsele = false;
      } else {
        this.orgNotsele = true;
      }
      var url = "/rps/cardFace/";
      if (
        this.actType != null &&
        (this.actType == "upd" || this.actType == "view")
      ) {
        url += this.selectedId + "/";
        this.$axios
          .get(
            url,
            {
              params: {}
            },
            {
              headers: {
                operator: this.$util.getLoginer().userid,
                withCredentials: true
              }
            }
          )
          .then(res => {
            let data = res.data;
            if (data.success) {
              this.formBean = data.data;
              this.firstLoadedData = JSON.stringify(this.formBean);
            } else {
              this.$error(data.message);
            }
          })
          .catch(err => {});
      }
    },

    /**
     * 下载excle模板
     */
    getDownloadSampleUrl() {
      this.$axios
        .get("/rps/cardApplyBatch/template/export/", {})
        .then(res => {
          let data = res.data;
          if (data.success) {
            this.downloadFileUrl = data.data;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    /**
     * 提交表单
     * @augments formName 表单名称
     */
    submitForm(e) {
      //
      this.$refs["form1"].validate(valid => {
        if (valid) {
          // 表单校验成功
          if (this.actType == "add") {
            if (!this.showTable) {
              this.$error("文件预览失败，不支持提交");
              return;
            }
            var url = "/rps/cardApplyPreview/" + this.previewId + "/";
            //
            // 开启提交表单的loading
            this.fullscreenLoading = true;
            this.$axios
              .post(
                url,
                {},
                {
                  headers: {
                    operator: this.$util.getLoginer().userid,
                    withCredentials: true
                  }
                }
              )
              .then(res => {
                let data = res.data;
                // 关闭提交表单的loading
                this.fullscreenLoading = false;
                if (data.success) {
                  this.$message({
                    message: "申请保存成功",
                    type: "success"
                  });
                  this.$emit("ok", {});
                } else {
                  this.$error(data.message);
                }
              })
              .catch(err => {
                this.fullscreenLoading = false;
              });
          }
        } else {
          // 表单校验失败
          // this.$error("数据校验失败.");
        }
      });
    },

    handleFileChange(file, fileList) {
      this.fileList = fileList.slice(-1);
    },

    /**
     * 上传excel文件
     */
    uploadFile(params) {
      let uploadForm = new FormData();
      uploadForm.append("files", params.file);
      this.$set(this.formBean, "operateFileName", params.file.name);
      this.$util.loadingshow();
      this.$axios
        .post("/rps/cardApplyResp/import/", uploadForm, {
          headers: {
            operator: this.$util.getLoginer().userid,
            withCredentials: true
          }
        })
        .then(res => {
          let data = res.data;
          if (data.success) {
            this.$message({
              type: "success",
              content: data.message
            });
          } else {
            this.$util.loadinghide();
            this.$error(data.message);
          }
        })
        .catch(err => {
          this.$util.loadinghide();
          console.log(err);
        });
    },

    getTableData() {
      this.$axios
        .get("/rps/cardApplyPreview/" + this.previewId + "/", {
          params: this.parampters,
          headers: {
            operator: this.$util.getLoginer().userid,
            withCredentials: true
          }
        })
        .then(res => {
          this.$util.loadinghide();
          let data = res.data;
          if (data.success) {
            this.tableData = data.data.list;
            this.showTable = true;
            this.parampters.pageIndex =
              data.data.pageNum != undefined ? parseInt(data.data.pageNum) : 0;
            this.parampters.pageCount =
              data.data.totalPage != undefined
                ? parseInt(data.data.totalPage)
                : 0;
            this.parampters.totalCount =
              data.data.count != undefined ? parseInt(data.data.count) : 0;
          } else {
            this.$error(data.message);
          }
        })
        .catch(err => {
          this.$util.loadinghide();
          console.log(err);
        });
    },

    changeColumnClass(data) {
      if (data.columnIndex == 1 || data.columnIndex == 2) {
        return "tabcolumn_left";
      }
    },

    /**
     * 通用定义:下拉字典
     *  @augments dictKind 字典类型
     */
    loadSelectOptoins(dictKind, params) {
      let url = "/rps/" + dictKind + "/";
      this.$axios
        .get(url, {
          params: params,
          headers: {
            operator: this.$util.getLoginer().userid,
            withCredentials: true
          }
        })
        .then(res => {
          let data = res.data;
          if (data.success) {
            this.$set(this.dicts, dictKind, data.data.list);
          } else {
            this.$error("查询失败" + data.message);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    initCityOptions(province) {
      if (province.provinceCode != this.parampters.provinceCode) {
        this.$set(this.parampters, "provinceCode", province.provinceCode);
        this.$set(this.parampters, "provinceName", province.provinceName);
        this.$set(this.parampters, "city", null);
        this.$set(this.parampters, "cityCode", "");
        this.$set(this.parampters, "cityName", "");
        let params = {
          provinceId: province.provinceId
        };
        this.canSelDnseg = false;
        this.loadSelectOptoins("city", params);
      }
    },

    changeCity(city) {
      if (city.cityCode != this.parampters.cityCode) {
        this.$set(this.parampters, "cityName", city.cityName);
        this.$set(this.parampters, "cityCode", city.cityCode);
        this.$set(this.parampters, "dnsegNum", "");
        this.canSelDnseg = true;
      }
    },

    changeSp(sp) {
      this.$set(this.parampters, "spNo", sp.spNo);
      this.$set(this.parampters, "spName", sp.spName);
    },

    changeCardFace(cardFace) {
      this.$set(this.parampters, "cardFaceName", cardFace.faceName);
      this.$set(this.parampters, "cardFaceId", cardFace.cardFaceId);
    },

    preSelDnesg() {
      if (!this.canSelDnseg) {
        this.$error("请先选择省市，后选择号段");
      } else {
        let params = {
          provinceCode: this.parampters.provinceCode,
          cityCode: this.parampters.cityCode
        };
        this.loadSelectOptoins("dnseg", params);
      }
    },

    /**
     * @augments val 页码
     * 切换页码操作
     */
    handleCurrentChange(val) {
      this.parampters.pageIndex = val;
      // 重新获取当前页码的数据
      this.getTableData();
    },

    /**
     * @augments val 每页显示条数
     * 每页显示条数修改
     */
    handleSizeChange(val) {
      // 修改每页显示条数
      this.parampters.pageRows = val;
      // 重新获取数据
      this.getTableData();
    },
    downloadFile() {
      let downloadUrl = this.downloadFileUrl;
      let n = downloadUrl.split("/");
      var link = document.createElement("a");
      //设置下载的文件名
      link.download = n[n.length - 1];
      link.style.display = "none";
      //设置下载路径
      link.href = downloadUrl;
      //浏览器兼容，禁止打开新的页面
      link.target = "_self";
      //触发点击
      document.body.appendChild(link);
      link.click();
      //移除节点
      document.body.removeChild(link);
    }
  }
};
</script>
